package util

import (
	"encoding/json"
	"errors"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
)

func SendSms(phone string, tplId string, param map[string]string) error {

	if client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou",
		"LTAI4GHR9ZuC8aNrp5E7wDW4", "QviKrFM61nzAb3gdNU9i3lMUvuRZkv"); err != nil {
		return err
	} else {
		request := dysmsapi.CreateSendSmsRequest()
		request.Scheme = "https"

		request.PhoneNumbers = phone
		request.SignName = "河南省药品评价中心"
		request.TemplateCode = tplId
		mjson, _ := json.Marshal(param)
		request.TemplateParam = string(mjson)

		if response, err := client.SendSms(request); err != nil {
			return err
		} else if response.Code != "OK" {
			return errors.New(response.Message)
		} else {
			return nil
		}
	}

	/*{
		"Message": "OK",
		"RequestId": "873043ac-bcda-44db-9052-2e204c6ed20f",
		"BizId": "607300000000000000^0",
		"Code": "OK"
	}
	*/
}

func SendBatchSms(phones []string, tplId string, signs []string, params []map[string]string) error {

	if client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou",
		"LTAI4GHR9ZuC8aNrp5E7wDW4", "QviKrFM61nzAb3gdNU9i3lMUvuRZkv"); err != nil {
		return err
	} else {
		request := dysmsapi.CreateSendBatchSmsRequest()
		request.Scheme = "https"

		phonesJson,_ := json.Marshal(phones)
		request.PhoneNumberJson = string(phonesJson)

		signsJson, _ := json.Marshal(signs)
		request.SignNameJson = string(signsJson)

		request.TemplateCode = tplId

		mjson, _ := json.Marshal(params)
		request.TemplateParamJson = string(mjson)

		if response, err := client.SendBatchSms(request); err != nil {
			return err
		} else if response.Code != "OK" {
			return errors.New(response.Message)
		} else {
			return nil
		}
	}

}
